import { Client, ConnectConfig } from "ssh2";
import { PWD } from "./pwd";

/**
 * SSHHandler
 */
class SSHHandler {
  public host: string;
  public port: string | number;
  public username: string;
  public pwd: string;
  public client: Client;

  constructor(host: string, port: string | number, username: string) {
    this.host = host ?? "127.0.0.1";
    this.port = port ?? "22";
    this.username = username ?? "root";
    this.pwd = PWD;
    let cconfig: ConnectConfig = {
      host: this.host,
      username: this.username,
      password: this.pwd,
    };

    //@ts-ignore
    this.client = new window.ssh2.Client();
    this.client.connect(cconfig);
    this.client.on("ready", () => {
      console.log("SSH connection established.");
    });
  }

  public executeCommand(command: string): Promise<string> {
    return new Promise((resolve, reject) => {
      this.client.exec(command, (err, stream) => {
        if (err) {
          reject(err);
        } else {
          let output = "";
          stream
            .on("data", (data: any) => {
              output += data.toString();
            })
            .on("close", (code: any, signal: any) => {
              if (code === 0) {
                resolve(output);
              } else {
                reject(`Command execution failed with code ${code}`);
              }
            })
            .stderr.on("data", (data) => {
              reject(data.toString());
            });
        }
      });
    });
  }
}

export { SSHHandler };
